package cn.tsvtc.springboot.service.impl;

import cn.tsvtc.springboot.entity.Category;

import cn.tsvtc.springboot.entity.GoodsTemple;
import cn.tsvtc.springboot.mapper.CategoryMapper;
import cn.tsvtc.springboot.mapper.GoodsMapper;
import cn.tsvtc.springboot.service.GoodsService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

/**
 * @author: Athena
 * @date: 2020/10/23 16:26
 * @description:
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;



    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    RedisTemplate redisTemplate;

    //1. 使用redis把商品列表数据放入缓存，在后期查询时通过缓存来获取数据
    //2. 增加商品时，把增加商品的数据更新到缓存
    @Override
    public List<GoodsTemple> getAll() {
        List<GoodsTemple> goodsTempleList=null;
        //先从redis找
        List<String> goodsList = redisTemplate.opsForList().range("goodsList", 0, -1);

        if (goodsList != null&&goodsList.size()>0) {
            System.out.println("从redis读到的，喵喵喵");
            goodsTempleList=new ArrayList<GoodsTemple>();
            for (String s : goodsList) {
                GoodsTemple goodsTemple= JSON.parseObject(s, GoodsTemple.class);
                goodsTempleList.add(goodsTemple);
            }


            return goodsTempleList;
        }else {
            System.out.println("从数据库读到的，旺旺旺");
            //没找到就从数据库读到并存入redis
            goodsTempleList = goodsMapper.selectAll();
            for (GoodsTemple goodsTemple : goodsTempleList) {
                redisTemplate.opsForList().leftPush("goodsList" ,JSON.toJSONString(goodsTemple));
            }
            //redisTemplate.opsForList().leftPush("goodsList" ,JSON.toJSONString(goodsTempleList));
            return goodsTempleList;
        }
    }

    @Override
    public int insert(GoodsTemple goodsTemple) {
        Category category = categoryMapper.selectByPrimaryKey(goodsTemple.getCid());
        goodsTemple.setCategory(category);
        //加入数据库
        int insert = goodsMapper.insert1(goodsTemple);
        System.out.println("数据库insert = " + insert);
        //成功就加入redis

        if(insert==1){


            Long result = redisTemplate.opsForList().leftPush("goodsList", JSON.toJSONString(goodsTemple));
            System.out.println("redis存入 = " + result);
        }
        return insert;
    }
}
